from django.http import FileResponse,StreamingHttpResponse
import re
import sqlite3
import os
import logging
from django.http import HttpResponse
from django.conf import settings
import json
import sys
import io

logging.basicConfig(level=logging.DEBUG,format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',datefmt='%a, %d %b %Y %H:%M:%S')
execShellDir='/export/datamarket/OozieProperties/oozie_project/oozie_shell/upload'
sys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='gb18030')
def file_download(request):

	if request.method == 'POST':
		try:	
			#received_json_data=json.loads(request.body.decode().replace("'", "\""))
			#logging.info("\n\n\n\t"+str(received_json_data)+"\n\n")
			#shellID=received_json_data['shellID']
			logging.info(request.body)
			shellID=json.loads(request.body.decode('utf8','ignore').replace("'","\""))
			logging.info(type(shellID))
			logging.info(type(shellID['shellID']))
			shellID=shellID['shellID']
			db_path = os.path.normpath('/export/datamarket/OozieProperties/oozie_project/db.sqlite3')
			db = sqlite3.connect(db_path) 
			# 通过cursor创建游标
			cursor = db.cursor()
			sql_shellID="select oozieShell from oozie_shell where shellID ={}".format(shellID)
			print(sql_shellID)
			cursor.execute(sql_shellID)
			oozieShell=cursor.fetchall()
			oozieShell=oozieShell[0][0]
			cursor.close()
			db.commit()
			db.close()
			def file_iterator(file_name, chunk_size=512):
				with open(file_name) as f:
					while True:
						c = f.read(chunk_size)
						if c:
							yield c
						else:
							break
			the_file_name = execShellDir+'/'+oozieShell
			response = StreamingHttpResponse(file_iterator(the_file_name))
			response['Content-Type'] = 'application/octet-stream'
			response['Content-Disposition'] = 'attachment;filename="{0}"'.format(the_file_name)
			return response
		except:
			logging.info('\n\n\n\t输入格式有误\n\n')
			resultError={'result':'没有次脚本','code':'1'}
			return HttpResponse(json.dumps(resultError,ensure_ascii=False))
	else:
		pass
